package cn.jfstu.freenote.mvc.interceptor;

import cn.jfstu.freenote.entity.extend.User;
import cn.jfstu.freenote.exception.extend.AppException;
import cn.jfstu.freenote.exception.message.ExceptionCode;
import cn.jfstu.freenote.mvc.annotation.DisableLoginCheck;
import cn.jfstu.freenote.mvc.assist.Session;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * 登录拦截器
 * 验证用户是否登录
 *
 * @author 贾俊峰
 * @version 1.0
 * @date 2016/9/18 14:09
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        DisableLoginCheck disableLoginCheck = method.getAnnotation(DisableLoginCheck.class);
        ResponseBody responseBody = method.getAnnotation(ResponseBody.class);
        if (disableLoginCheck == null) {
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute(Session.LOGIN_USER);
            if (user == null) {
                if (responseBody == null) {
                    response.sendRedirect("login");
                    return false;
                } else {
                    throw new AppException(ExceptionCode.NO_LOGIN);
                }
            }
        }
        return true;
    }
}
